package com.inspur.oss.utils;

import lombok.Data;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

@Data
public class DBUtils {

    private static String driver;

    private static String url;

    private static String username;

    private static String password;

    static {
        try{
            InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");

            Properties properties = new Properties();
            properties.load(inputStream);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws Exception{
        Connection connection = null;

        Class.forName(driver);
        connection = DriverManager.getConnection(url,username,password);

        return connection;
    }

    public static void CloseConnectionResource(Connection connection) throws Exception{
        if(connection != null){
            connection.close();
        }
    }

    public static ResultSet executePrepareQuery(Connection connection,String sql,Object[] params) throws Exception{
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i,params[i]);
        }
        return preparedStatement.executeQuery();
    }

    public static boolean executePrepare(Connection connection,String sql,Object[] params) throws Exception{
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        return preparedStatement.execute();
    }
}
